package com.caus.activities;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Build;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.caus.entities.User;
import com.caus.integration.android.IntentIntegrator;
import com.caus.services.ServiceController;
import com.caus.utils.Codigos;

public class Main extends Activity implements SensorEventListener,OnClickListener{

	private boolean mInitialized;
	private SensorManager mSensorManager;
	private Sensor mAccelerometer;
	private String barcode="";
	private static Context context;
	
	OnClickListener listener1 = null;
	OnClickListener listener2 = null;
	OnClickListener  listenerConfig = null;
	Button login;
	Button qr_button;
	Button btnConfig;
	ImageView  imageView;

	
	/** Called when the activity is first created. */
	@TargetApi(Build.VERSION_CODES.GINGERBREAD)
	@SuppressLint("NewApi")
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		context= getApplicationContext();
		
		setContentView(R.layout.login);
		//setContentView(R.layout.main);
		mInitialized = false;
		mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
		mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
		//mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
		mSensorManager.registerListener(this, mAccelerometer,
				SensorManager.SENSOR_DELAY_NORMAL);
		
		setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		
		StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
	     .detectAll()
	     .penaltyLog()
	     .build();
		StrictMode.setThreadPolicy(policy);
	
		//TODO:Borrar luego, solo  para prueba
		TextView txtUser=(TextView)findViewById(R.id.textViewUser);
		txtUser.setText("caste86@gmail.com");
		//txtUser.setText("szazs@ort.edu.com.uy");
		TextView txtPass=(TextView)findViewById(R.id.textViewPassword);
		txtPass.setText("123");
	
		
        listener2 = new OnClickListener() {
            public void onClick(View v) {
            	TextView txtUser=(TextView)findViewById(R.id.textViewUser);
        		TextView txtPass=(TextView)findViewById(R.id.textViewPassword);
        		User loguedUser = ServiceController.getInstance().getLoguedUser(txtUser.getText().toString(), txtPass.getText().toString());
        		ServiceController.getInstance().setLoguedUser(loguedUser);
        		if(txtUser.getText().equals("")||txtPass.getText().equals("")){
        			if(txtUser.getText().equals("")){
        				txtUser.setError("Por favor ingrese un nombre de usuario");
        			}if(txtPass.getText().equals("")){
        				txtUser.setError("Por favor ingrese un password");
        			}
        			
        		}else{
        			if(loguedUser!=null){
		            	if(loguedUser.getEmail()!=null){
		            		//TODO:  Agregar pantalla Bienvenido user XXX.
		            		ServiceController.getInstance().setLoguedUser(loguedUser);
			            	Intent myIntent = new Intent(Main.this, QRProcess.class);
			            	//myIntent.putExtra(Codigos.CODIGO_USUARIO, txtUser.getText().toString());
			            	Main.this.startActivity(myIntent);
		            	}else{
		            		//TODO: Mensaje user o pass incorrectos como en setear disponibilidad
		            		txtUser.setError("Usuario o Password incorrectos");
		            		txtPass.setError("Usuario o Password incorrectos");
		            		Toast.makeText(getApplicationContext(), "Usuario o contrasenia incorrectos", Toast.LENGTH_LONG).show();
		            	}
        			}else{
        				Toast.makeText(getApplicationContext(), "Problemas al conectarse al servidor. verifique los datos de conexion.", Toast.LENGTH_LONG).show();
        			}
        		}
            }
        };
        
        listenerConfig = new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent myIntent = new Intent(Main.this, Configuracion.class);
            	Main.this.startActivity(myIntent);
			}
		};
        login =(Button)findViewById(R.id.btnLogin);
        login.setOnClickListener(listener2);

        btnConfig=(Button)findViewById(R.id.btnConfig);
        btnConfig.setOnClickListener(listenerConfig);
	}
	
	
	
	protected void onResume() {
		super.onResume();
		mSensorManager.registerListener(this, mAccelerometer,
				SensorManager.SENSOR_DELAY_NORMAL);
	}

	protected void onPause() {
		super.onPause();
		mSensorManager.unregisterListener(this);
		
	}

	@Override
	public void onAccuracyChanged(Sensor sensor, int accuracy) {
		// can be safely ignored for this demo
	}

	@Override
	public void onClick(View v) {
		Toast.makeText(getApplicationContext(), "Ando!", Toast.LENGTH_LONG).show();
		
		IntentIntegrator integrator = new IntentIntegrator(this);
    	integrator.initiateScan();
		
	}

	@Override
	public void onSensorChanged(SensorEvent event) {
		// TODO Auto-generated method stub
		
	}
	
	@Override
	public void onRestoreInstanceState(Bundle savedInstanceState) {
	  super.onRestoreInstanceState(savedInstanceState);
	    // Restore UI state from the savedInstanceState.
	    // This bundle has also been passed to onCreate.
		//	  String myString = savedInstanceState.getString("imageID");
		//	  if(!myString.equals("")){
		//	  
		//		  ImageView imageView= (ImageView)findViewById(R.id.imageView1);
		//	
		//	      File sdCard = Environment.getExternalStorageDirectory();
		//			File dir = new File (sdCard.getAbsolutePath()+ "/imagenesOrt/"+myString+".jpg");
		//			
		//			Bitmap bmpPosta = decodeFile(dir,400,300);
		//	      		
		//			Drawable verticalImage = new BitmapDrawable(getResources(), bmpPosta);
		//	      
		//			imageView.setImageDrawable(verticalImage);
		//	  }

	}


	public String getBarcode() {
		return barcode;
	}


	public void setBarcode(String barcode) {
		this.barcode = barcode;
	}
	
	public static Context getAppContext() {
        return Main.context;
    }
	
}